package com.ruoyi.common.wxUtils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;

import com.ruoyi.common.core.redis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;

@Component
public class WxRedisAccessToken {

    @Autowired
    private RedisCache redisCache;

    private final static String appId="wx53c8258f2611c2ef";
    private final static String secret="2ba0d9c253571ce7bed7690702b69d1b";

    public String getWxAccessToken() {
        String accessToken = null;
        if (redisCache.getCacheObject("mini_program_access_token") != null) {
            accessToken = redisCache.getCacheObject("mini_program_access_token");
        } else {
            RestTemplate restTemplate = new RestTemplate();
            String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + secret;
            String json = restTemplate.getForObject(url, String.class);
            System.out.println("微信小程序===>获取accessToken返回===>{}"+json);
            JSONObject resultJson = JSON.parseObject(json);
            System.out.println("微信小程序===>JSON解析获取accessToken后的数据===>{}"+ resultJson);
            if (resultJson.containsKey("access_token")) {
                accessToken = resultJson.getString("access_token");
                redisCache.setCacheObject("mini_program_access_token", accessToken, 100, TimeUnit.SECONDS);
            } else {
                System.out.println("[微信 getAccessToken] 回复失败 回复报文：" + json);
            }
        }
        return accessToken;
    }
}
